package com.hanserwei.han_picture.controller;

import com.hanserwei.han_picture.domain.common.ApiResponse;
import com.hanserwei.han_picture.domain.entity.po.User;
import com.hanserwei.han_picture.service.UserService;
import com.hanserwei.han_picture.websocket.WebSocketMessageService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * WebSocket相关接口
 *
 * @author hanserwei
 */
@RestController
@RequestMapping("/websocket")
@RequiredArgsConstructor
@Tag(name = "WebSocketController")
public class WebSocketController {

    private final WebSocketMessageService webSocketMessageService;
    private final UserService userService;

    @Operation(summary = "获取WebSocket连接信息")
    @GetMapping("/connection-info")
    public ApiResponse<Map<String, Object>> getConnectionInfo(HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);

        Map<String, Object> info = new HashMap<>();
        info.put("wsUrl", "/ws/ai-process");
        info.put("userId", loginUser.getId());
        info.put("connectionParams", "userId=" + loginUser.getId());
        info.put("fullWsUrl", "ws://localhost:8088/api/ws/ai-process?userId=" + loginUser.getId());

        return ApiResponse.success("获取WebSocket连接信息成功", info);
    }

    @Operation(summary = "获取WebSocket连接状态")
    @GetMapping("/status")
    public ApiResponse<Map<String, Object>> getWebSocketStatus(HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);

        Map<String, Object> status = new HashMap<>();
        status.put("totalConnections", webSocketMessageService.getConnectionCount());
        status.put("userOnline", webSocketMessageService.isUserOnline(loginUser.getId()));
        status.put("userId", loginUser.getId());

        return ApiResponse.success("获取WebSocket状态成功", status);
    }
}
